package com.patrick.open.api.core.common;

import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.google.common.collect.Maps;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.Serializable;
import java.util.Map;


@Slf4j
@Data
@ApiModel(value = "响应结果")
public class RespData<T> implements Serializable {

  private static final long serialVersionUID = 0521;

  /**
   * 响应编码
   */
  @ApiModelProperty(value = "响应编码:0000-请求处理成功")
  private int code = 0000;
  /**
   * 提示消息
   */
  @ApiModelProperty(value = "响应消息")
  private String msg;

  /**
   * 请求路径
   */
  @ApiModelProperty(value = "请求路径")
  private String path;

  /**
   * 响应数据
   */
  @ApiModelProperty(value = "响应数据")
  private T data;

  /**
   * http状态码
   */
  private int httpStatus;

  /**
   * 附加数据
   */
  @ApiModelProperty(value = "附加数据")
  private Map<String, Object> extra;

  /**
   * 响应时间
   */
  @ApiModelProperty(value = "响应时间")
  private long timestamp = System.currentTimeMillis();

  public RespData() {
    super();
  }

  public int getCode() {
    return code;
  }

  public String getMsg() {
    return msg;
  }

  public String getPath() {
    return path;
  }

  public T getData() {
    return data;
  }

  public Map<String, Object> getExtra() {
    return extra;
  }

  public long getTimestamp() {
    return timestamp;
  }

  @JSONField(serialize = false, deserialize = false)
  @JsonIgnore
  public int getHttpStatus() {
    return httpStatus;
  }

  @JSONField(serialize = false, deserialize = false)
  @JsonIgnore
  public boolean isOk() {
    return this.code == RespCode.OK.getCode();
  }


  public static RespData ok() {
    return new RespData().code(RespCode.OK.getCode()).msg(RespCode.OK.getMsg());
  }

  public static RespData failed() {
    return new RespData().code(RespCode.FAIL.getCode()).msg(RespCode.FAIL.getMsg());
  }

  public RespData code(int code) {
    this.code = code;
    return this;
  }

  public RespData msg(String msg) {
    this.msg = msg;
    return this;
  }

  public RespData data(T data) {
    this.data = data;
    return this;
  }

  public RespData path(String path) {
    this.path = path;
    return this;
  }

  public RespData httpStatus(int httpStatus) {
    this.httpStatus = httpStatus;
    return this;
  }

  public RespData put(String key, Object value) {
    if (this.extra == null) {
      this.extra = Maps.newHashMap();
    }
    this.extra.put(key, value);
    return this;
  }

}
